<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>动态组件</h2>
      <!-- <button @click="active = 1">btn1</button>
      <button @click="active = 2">btn2</button>
      <button @click="active = 3">btn3</button>
      <hr /> -->
      <!-- <child1 v-if="active === 1"></child1>
      <child2 v-if="active === 2"></child2>
      <child3 v-if="active === 3"></child3> -->

      <button @click="compName = 'Child1'">btn1</button>
      <button @click="compName = 'Child2'">btn2</button>
      <button @click="compName = 'Child3'">btn3</button>
      <hr />
      <!-- 可以使用component的标签来做内容切换 -->
      <!-- 里面需要is属性，is属性里面写字符串，字符串的值如果和组件名相同，那么那个组件就会替换component -->
      <!-- 用动态组件显示和隐藏组件的时候，那么组件是会挂载和销毁的 -->
      <!-- keep-alive叫做缓存组件 -->
      <keep-alive>
        <component :is="compName"></component>
      </keep-alive>
    </div>

    <script src="./lib/vue3.js"></script>
    <script>
      const { createApp } = Vue;

      const Child1 = {
        template: `
          <div>child子组件1</div>
        `,
      };

      let timer;
      const Child2 = {
        data() {
          return {
            count: 1,
          };
        },
        mounted() {
          console.log("child2 mounted");
          // setInterval(() => {
          //   this.count++;
          // }, 1000);
        },
        beforeUnmount() {
          console.log("child2 unmount");
        },
        // 缓存组件被激活(插入dom)时调用
        activated() {
          console.log("child2 activated");
          timer = setInterval(() => {
            this.count++;
          }, 1000);
        },
        // 缓存组件被失活(移除dom)时调用
        deactivated() {
          console.log("child2 deactivated");
          clearInterval(timer);
        },
        template: `
          <div>child子组件2 - {{ count }} - <button @click="count++">btn</button></div>
        `,
      };

      const Child3 = {
        template: `
          <div>child子组件3</div>
        `,
      };

      createApp({
        data() {
          return {
            // active: 1,
            compName: "Child1",
          };
        },
        components: {
          Child1,
          Child2,
          Child3,
        },
      }).mount("#app");
    </script>
  </body>
</html>
